package com.zy.imagineCommunity.controller;

import com.alibaba.fastjson.JSONObject;
import com.zy.imagineCommunity.entity.User;
import com.zy.imagineCommunity.service.UserSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.nio.charset.StandardCharsets;

@Controller
public class UserController {

    @Autowired
    UserSerivce userSerivce;

    //注入路径域名
    @Value("${ImagineCommunity.path.domain}")
    private String domain;

    @GetMapping("/updateHead")
    public String updateHeadImg() {
        return "/updateHeadImg";
    }

    /**
     * 设置用户头像
     *
     * @param userId
     * @param file
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("/setHeadImg")
    protected JSONObject setHeadImg(int userId, MultipartFile file, HttpServletRequest request) {
        //最终存入数据库的图片地址
        String filepath = null;

        if (!file.isEmpty()) {
            try {
                // 时间戳
                String[] st = file.getOriginalFilename().split("\\.");
                int suffixIndex = st.length - 1;
                String exe = st[suffixIndex];
                Long timeStamp = System.currentTimeMillis();

                System.out.println("上传的文件名：" + file.getOriginalFilename());

                String fileName = timeStamp + "." + exe;
                String filePath = "e:\\test\\" + fileName;

                System.out.println("修改的文件名：" + filePath);
                System.out.println("/ImagineCommunity/test/" + fileName);

                filepath = "/ImagineCommunity/test/" + fileName;

                File saveFile = new File(filePath);
                if (!saveFile.getParentFile().exists())
                    saveFile.getParentFile().mkdirs();
                file.transferTo(saveFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        User userOne = userSerivce.queryUserByUserId(userId);

        userSerivce.updateUserByUserId(new User(userOne.getId(), userOne.getUsername(), userOne.getPassword(), userOne.getEmail(), filepath, userOne.getCreateTime(), userOne.getUserStatus(), userOne.getLanguageState(), userOne.getMessageNum()));

        User userTwo = userSerivce.queryUserByUserId(userId);

        HttpSession session = request.getSession();

        session.setMaxInactiveInterval(60 * 60 * 12);

        session.setAttribute("user", userTwo);

        JSONObject jsonObject = new JSONObject();

        return jsonObject;

    }

    @GetMapping("/updateUserName")
    public String updateUserName() {
        return "/updateUserName";
    }

    /**
     * 设置用户名称
     *
     * @param userId
     * @param userName
     * @return
     */
    @ResponseBody
    @PostMapping("/setUserName")
    protected JSONObject setUserName(int userId, String userName, HttpServletRequest request) {

        User user = userSerivce.queryUserByUserId(userId);

        userSerivce.updateUserByUserId(new User(user.getId(), userName, user.getPassword(), user.getEmail(), user.getHeadImg(), user.getCreateTime(), user.getUserStatus(), user.getLanguageState(), user.getMessageNum()));

        User userTwo = userSerivce.queryUserByUserId(userId);

        HttpSession session = request.getSession();

        session.setMaxInactiveInterval(60 * 60 * 12);

        session.setAttribute("user", userTwo);

        JSONObject jsonObject = new JSONObject();

        return jsonObject;
    }

    @GetMapping("/updatePassWord")
    public String updatePassWord() {
        return "/updatePassWord";
    }

    /**
     * 设置用户密码
     *
     * @param userId
     * @param passWord
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("/setPassWord")
    protected JSONObject setPassWord(int userId, String oldPassWord, String passWord, HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();

        User user = userSerivce.queryUserByUserId(userId);

        String MD5oldPassWord = DigestUtils.md5DigestAsHex(oldPassWord.getBytes());

        if (!MD5oldPassWord.equals(user.getPassword())) {
            jsonObject.put("msg", "no");
            return jsonObject;
        }

        if (MD5oldPassWord.equals(user.getPassword())) {
            String MD5passWord = DigestUtils.md5DigestAsHex(passWord.getBytes());

            userSerivce.updateUserByUserId(new User(user.getId(), user.getUsername(), MD5passWord, user.getEmail(), user.getHeadImg(), user.getCreateTime(), user.getUserStatus(), user.getLanguageState(), user.getMessageNum()));

            User userTwo = userSerivce.queryUserByUserId(userId);

            HttpSession session = request.getSession();

            session.setMaxInactiveInterval(60 * 60 * 12);

            session.setAttribute("user", userTwo);

            jsonObject.put("msg", "yes");

            return jsonObject;
        }

        return jsonObject;
    }

    @GetMapping("/personalInformation")
    public String personalInformation() {
        return "/personalInformation";
    }

}
